package com.ykyl.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.ykyl.constant.JwtTokenManagerConstant;
import com.ykyl.constant.UserCacheConstant;
import com.ykyl.exceptions.UnauthorizedException;
import com.ykyl.pojo.dto.LoginDto;
import com.ykyl.pojo.vo.ResourceVo;
import com.ykyl.pojo.vo.RoleVo;
import com.ykyl.pojo.vo.UserAuth;
import com.ykyl.pojo.vo.UserVo;
import com.ykyl.service.LoginService;
import com.ykyl.service.ResourceService;
import com.ykyl.service.RoleService;
import com.ykyl.utils.JwtUtil;
import com.ykyl.utils.UUID;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class LoginServiceImpl implements LoginService {

    private final AuthenticationManager authenticationManager;

    private final ResourceService resourceService;

    private final RoleService roleService;

    private final StringRedisTemplate redisTemplate;


    /**
     * 后台用户登录
     *
     * @param loginDto
     * @return
     */
    @Override
    public UserVo login(LoginDto loginDto) {

        //使用认证管理器来进行认证
        UsernamePasswordAuthenticationToken upat = new UsernamePasswordAuthenticationToken(loginDto.getUsername(), loginDto.getPassword());
        Authentication authenticate = authenticationManager.authenticate(upat);
        if (!authenticate.isAuthenticated()) {
            throw new UnauthorizedException("用户登录失败");
        }
        //获取用户数据
        UserAuth userAuth = (UserAuth) authenticate.getPrincipal();
        UserVo userVo = BeanUtil.toBean(userAuth, UserVo.class);

        //获取用户的资源列表
        List<ResourceVo> resourceVoList = resourceService.findResourceVoListByUserId(userVo.getId());
        Set<String> resourceRequestPaths = resourceVoList.stream()
                .filter(r -> "r".equals(r.getResourceType()))
                .map(ResourceVo::getRequestPath)
                .collect(Collectors.toSet());

        userVo.setResourceRequestPaths(resourceRequestPaths);

        //获取用户的角色列表
        List<RoleVo> roleVoList = roleService.findRoleVoListByUserId(userVo.getId());
        Set<String> roleLabels = roleVoList.stream().map(RoleVo::getLabel).collect(Collectors.toSet());
        userVo.setRoleLabels(roleLabels);
        userVo.setRoleList(roleVoList);


        //生成token   jwttoken  uuidtoken
        String uuidToken = UUID.randomUUID().toString();
        userVo.setUserToken(uuidToken);

        //敏感数据处理
        userVo.setPassword("");

        Map<String, Object> clamis = new HashMap<>();
        clamis.put("currentUser", JSONUtil.toJsonStr(userVo));

        String jwtToken = JwtUtil.createJWT(JwtTokenManagerConstant.SECRET_KEY
                , JwtTokenManagerConstant.TTL, clamis);

        //过期时间计算
        long ttl = Long.valueOf(JwtTokenManagerConstant.TTL / 1000);

        String userTokenkey = UserCacheConstant.USER_TOKEN + userVo.getUsername();

        redisTemplate.opsForValue().set(userTokenkey, uuidToken, ttl, TimeUnit.SECONDS);

        String jwtTokenKey = UserCacheConstant.JWT_TOKEN + uuidToken;

        redisTemplate.opsForValue().set(jwtTokenKey, jwtToken, ttl, TimeUnit.SECONDS);

        return userVo;
    }
}
